package fr.labri.harmony.analysis.jsep.results.filter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import fr.labri.harmony.analysis.jsep.results.LoadRules;
import fr.labri.harmony.analysis.jsep.results.ProjectActivity;
import fr.labri.harmony.analysis.jsep.results.filter.CorpusMigrantsStatsSummary.DataProject;

public class MigrationCategories extends ResultFilter {

	@Override
	public void computeResult(ResultSet rs) throws SQLException, IOException {

		Map<String, Set<String>> usage_libs = new HashMap<String, Set<String>>();
		rs.first();
		while (rs.next()){			
			String project = rs.getString("PROJECT");
			String libs_used = rs.getString("LAST_LIBS").replaceAll(" ", "");
			Set<String> libs =  Utils.filterLibs(libs_used.replaceAll("\\[", "").replaceAll("\\]", "").split("\\,"));
			for(String lib : libs) {
				if(!usage_libs.containsKey(lib)) usage_libs.put(lib, new HashSet<String>());
				usage_libs.get(lib).add(project);
			}
		}

		PrintStream ps = new PrintStream(new FileOutputStream("categories.csv"));
		ps.println("ID ; SIZE ; MIGRATIONS ; CLIENTS ; CONTENT");
		int cpt=0;
		for(Set<String> cat : LoadRules.getCategories()) {
			cpt++;
			int migrations=0;
			for(String s : cat)
				for(String t : cat)
					if(LoadRules.getScore(s,t) != null)
						migrations+=LoadRules.getScore(s,t);
			ps.println(cpt+ ";" + cat.size() + ";" + migrations + ";" + getCategorySize(usage_libs, cat) + " ; "+cat.toString());
		}
		ps.close();
	}

	private int getCategorySize(Map<String, Set<String>> usage_libs, Set<String> cat) {
		Set<String> cliens = new HashSet<String>();
		for(String l : cat) 
			cliens.addAll(usage_libs.get(l));
		return cliens.size();
	}

}
